package tree.递归;

import po.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author songZiHao
 * @version 1.0.0
 * @ClassName 序列化和反序列化二叉搜索树449.java
 * @Description https://leetcode-cn.com/problems/serialize-and-deserialize-bst/
 * @createTime 2021年04月27日 12:56:00
 */
public class 序列化和反序列化二叉搜索树449 {
    // Encodes a tree to a single string.
    public static String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        serialize(root, sb);
        return sb.toString();
    }

    private static void serialize(TreeNode root, StringBuilder sb) {
        if (root == null) {
            sb.append("#").append(",");
            return;
        }
        sb.append(root.val).append(",");
        serialize(root.left,sb);
        serialize(root.right,sb);
    }

    // Decodes your encoded data to tree.
    public static TreeNode deserialize(String data) {
        String[] strings = data.split(",");
        Queue<String> queue = new LinkedList<>();
        for (String string : strings) {
            queue.offer(string);
        }
        return deserialize(queue);
    }

    private static TreeNode deserialize(Queue<String> queue) {
        if (queue.isEmpty()) {
            return null;
        }
        String poll = queue.poll();
        if (poll.equals("#")) {
            return null;
        }
        TreeNode treeNode = new TreeNode(Integer.valueOf(poll));
        treeNode.left = deserialize(queue);
        treeNode.right = deserialize(queue);
        return treeNode;
    }

    public static void main(String[] args) {
        TreeNode node = new TreeNode(2);
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(3);
        node.left=node1;
        node.right=node2;
        String serialize = serialize(node);
        System.out.println(serialize);
        TreeNode deserialize = deserialize("2,1,#,#,3,#,#,");
        System.out.println(deserialize);
    }
}
